# -*- coding: utf-8 -*-
import os
import time

from prologixGpibEthernet import GPIB
from config.preferences import SRC_PATH


class VNA8712ET(GPIB):

    def __init__(self, ui):
        """
            Construtor da classe.
        """
        self.ui = ui
        GPIB.__init__(self, ui)
        self.startUpConfig()
        self.recallProgram()



    def _connect(self):
        """
            Metodo interno para conexao do network analyzer.
        """
        self.connect('10.0.0.2')
        self.select(16)
        self.write("*CLS;")



    def startUpConfig(self):
        """
            Metodo que executa as configuracoes iniciais para o VNA.
        """
        self._connect()
        self.write("HCOP:DEV:LANG HPGL;PORT GPIB;")
        self.write("DISP:ANN:CLOC:MODE LINE2;")
        self.write("DISP:ANN:CLOC:DATE:FORM YMD;")
        self.write("DISP:ANN:CLOC:SEC 0;")
        self.write("DISP:ANN:CHAN 1 ON;")
        self.closeConnection()



    def recallProgram(self):
        """
            Metodo para fazer um recall no programa prg6.bas. Programa fica na 
            primeira posicao da memoria nao-volatil do VNA.
        """
        self._connect()
        self.write("SYST:KEY SAVE;")
        self.write("SYST:KEY SOFT5;")
        self.write("SYST:KEY SOFT4;")
        time.sleep(1.5)
        self.write("SYST:KEY SOFT8;")
        self.closeConnection()




    def plotLabel(self, produto, numAntena):
        """
        
        """
        self._connect()
        self.write("DISP:WIND1:GRAP:CLE")
        num_serie = ("%s-%s") % (numAntena[0], numAntena[1])
        line = ("DISP:ANN:TITL1:DATA '%s - Serial:%s'") % (produto, num_serie)
        self.write(line)
        self.flush()
        line = ("DISP:WIND:GRAP:LAB 'TSM ANTENNAS'")
        self.write(line)
        self.flush()
        self.closeConnection()



    def getPlot(self):
        """
            Metodo para a transferencia do plot para o computador.
        """
        self._connect()
        self.ui.progressBar.setValue(10)
        self.write("SENS:STAT ON; *WAI;")
        self.write("PROG:STAT RUN;")
        self._write("++mode 0\n")
        self._write("++addr 5\n")
        data = self.readPlot()
        os.chdir(SRC_PATH + '/tmp')
        plot = open("plot.hp", "w")
        plot.write(data)
        plot.close()
        os.system(
        "hp2xx -q -w200 -h200 -c44221422 -p12345678 -m jpg plot.hp --outfile plot.jpg")
        os.chdir(SRC_PATH)
        self.closeConnection()
